package com.daji.base_data_structure.Stack;

import java.util.Iterator;

public class Stack<T> implements Iterable<T> {

    // 记录首结点
    private Node head;
    // 栈中元素的个数
    private int N;

    public Stack() {
        head = new Node(null, null);
        N = 0;
    }

    private class Node {
        private T item;
        private Node next;

        public Node(T item, Stack<T>.Node next) {
            this.item = item;
            this.next = next;
        }
    }

    /**
     * 判断栈是否为空，是返回true，否返回false
     * 
     * @return
     */
    public boolean isEmpty() {
        return head.next == null;
    }

    /**
     * 获取栈中元素的个数
     * 
     * @return
     */
    public int size() {
        return N;
    }

    /**
     * 弹出栈顶元素
     * 
     * @return
     */
    public T pop() {
        Node oldNext = head.next;
        if(oldNext == null){
            return null;
        }
        //删除首个元素
        head.next = head.next.next;
        //个数--
        N--;
        return oldNext.item;
    }

    /**
     * 向栈中压入元素t
     * 
     * @param t
     */
    public void push(T t) {
        Node oldNext = head.next;
        Node node = new Node(t, oldNext);
        head.next = node;
        //个数+1
        N++;        
    }

    

    /*
     * 设计这个迭代器，要考虑到栈的出栈顺序是后进先出的特性。
     */
    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {

            //定义工作指针方便遍历。
            private Node workNode = head.next;

            @Override
            public boolean hasNext() {
                return workNode != null;
            }

            @Override
            public T next() {
                T ele = workNode.item;
                workNode = workNode.next;
                return ele;
            }

        };
    }

}
